﻿using System;
using System.Linq;
using log4net;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace SharePoint.Orm.Helpers {
	public static class SPUserHelper {
		private static readonly ILog _log = LogManager.GetLogger(typeof(SPUserHelper));

		public static bool IsUserInAtLeastOneGroup(SPUser user, params string[] groups) {
			return user.Groups
				.Cast<SPGroup>()
				.Any(g => groups.Any(groupName => string.Equals(groupName, g.Name, StringComparison.InvariantCultureIgnoreCase)));
		}

		/// <summary>
		/// Similar to <see cref="IsUserInAtLeastOneGroup"/> except that this method calls
		/// <see cref="SPUtility.HandleAccessDenied"/> if the user is not in a group.
		/// </summary>
		/// <param name="user"></param>
		/// <param name="groups"></param>
		public static void EnsureUserIsInAtLeastOneGroup(SPUser user, params string[] groups) {
			if (!IsUserInAtLeastOneGroup(user, groups)) {
				SPUtility.HandleAccessDenied(new SPOrmException("User must be in at least one of these groups \"" + string.Join(", ", groups) + "\""));
			}
		}
	}
}
